package com.htgd.gardenexpo.controller;

import cn.xuyanwu.spring.file.storage.FileInfo;
import cn.xuyanwu.spring.file.storage.FileStorageService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.htgd.gardenexpo.entity.*;
import com.htgd.gardenexpo.service.GeConTouristNoticeFeedbackService;
import com.htgd.gardenexpo.service.GeConTouristNoticeService;
import com.htgd.gardenexpo.service.GeConTouristNoticeUploadService;
import com.htgd.gardenexpo.utils.GetAmazonS3Client;
import com.htgd.gardenexpo.utils.SecurityParameter;
import com.htgd.gardenexpo.utils.UniteUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author ：hejing
 * @date ：Created in 2021/5/24 17:12
 * @description：入园须知管理
 * @menu: 入园须知管理
 * @modified By：`
 * @version: 1.0
 */
@Api(tags = "入园须知管理")
@RestController
@RequestMapping("/api/notice")
public class NoticeController {

    @Value("${upload.absolute.url}")
    public String absolute_url;
    @Value("${local.url}")
    public String local_url;

    @Value("${upload.url}")
    public String upload_url;
    @Value("${spring.file-storage.aws-s3[0].bucket-name}")
    public String bucket_name;

    @Autowired
    private FileStorageService fileStorageService;

    @Resource
    private GetAmazonS3Client getAmazonS3Client;

    @Resource
    private GeConTouristNoticeService geConTouristNoticeService;

    @Resource
    private GeConTouristNoticeUploadService geConTouristNoticeUploadService;

    @Resource
    private GeConTouristNoticeFeedbackService geConTouristNoticeFeedbackService;
    /**
     * 新增入园须知
     */
    @PostMapping(value = "/add")
    public CommonResult<JSONObject> add(@RequestBody GeConTouristNotice geConTouristNotice){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            String uploadIds=geConTouristNotice.getUploadIds();
            geConTouristNoticeService.insert(geConTouristNotice);
            if (!uploadIds.equals("")){
                for (String uploadId:uploadIds.split(",")){
                    GeConTouristNoticeUpload geConTouristNoticeUpload =geConTouristNoticeUploadService.queryById(Integer.parseInt(uploadId));
                    geConTouristNoticeUpload.setNoticeId(geConTouristNotice.getNoticeId());
                    geConTouristNoticeUploadService.update(geConTouristNoticeUpload);
                }
            }
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 上传图片
     */
   /* @PostMapping(value = "/uploadNewsPhoto")
    public String uploadNewsPhoto(@RequestParam(value = "file") MultipartFile file){
        if (file.isEmpty()) {
            System.out.println("文件为空");
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = absolute_url; // 上传后的路径
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return local_url+"upload/"+fileName;
    }*/
    /**
     * 上传文件
     */
    @PostMapping(value = "/uploadNoticeFile")
    public GeConTouristNoticeUpload uploadNoticeFile(@RequestParam(value = "file") MultipartFile file){

        GeConTouristNoticeUpload geConTouristNoticeUpload = new GeConTouristNoticeUpload();
        String fileName = file.getOriginalFilename();  // 文件名
        geConTouristNoticeUpload.setFilename(fileName);
        FileInfo fileInfo=fileStorageService.of(file)
                .setPlatform("aws-s3-1")
                .setSaveFilename(System.currentTimeMillis()+"/"+file.getOriginalFilename())
                .upload();
        geConTouristNoticeUpload.setFilePath(upload_url+fileInfo.getFilename());
        geConTouristNoticeUploadService.insert(geConTouristNoticeUpload);
        return geConTouristNoticeUpload;
    }

    /**
     * 编辑入园须知
     */
    @PostMapping(value = "/edit")
    public CommonResult<JSONObject> edit(@RequestBody GeConTouristNotice geConTouristNotice){
        CommonResult<JSONObject> result = new CommonResult<>();
        try{
            String uploadIds=geConTouristNotice.getUploadIds();
            geConTouristNoticeService.update(geConTouristNotice);
            if (!uploadIds.equals("")&&uploadIds.contains(",")){
                geConTouristNoticeUploadService.deleteByIds(uploadIds.split(","),geConTouristNotice.getNoticeId());
                for (String uploadId:uploadIds.split(",")){
                    GeConTouristNoticeUpload geConTouristNoticeUpload =geConTouristNoticeUploadService.queryById(Integer.parseInt(uploadId));
                    geConTouristNoticeUpload.setNoticeId(geConTouristNotice.getNoticeId());
                    geConTouristNoticeUploadService.update(geConTouristNoticeUpload);
                }
            }else {
                geConTouristNoticeUploadService.deleteByNoticeId(geConTouristNotice.getNoticeId());
            }
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 删除入园须知
     */
    @PostMapping(value = "/delete")
    public CommonResult<JSONObject> delete(int noticeId){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            geConTouristNoticeService.deleteById(noticeId);
            List<GeConTouristNoticeUpload> list=geConTouristNoticeUploadService.queryByNoticeId(noticeId);
            for (GeConTouristNoticeUpload geConTouristNoticeUpload:list){
                String filepath=geConTouristNoticeUpload.getFilePath();
                String path=filepath.substring(filepath.indexOf(bucket_name+"/"),filepath.length()-1);
                getAmazonS3Client.delete(path);
            }
            geConTouristNoticeUploadService.deleteByNoticeId(noticeId);
            geConTouristNoticeFeedbackService.deleteByNoticeId(noticeId);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 批量删除入园须知
     */
//    @PostMapping(value = "/deleteAll")
    public CommonResult<JSONObject> deleteAll(String noticeIds){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            if (noticeIds!=null&&!noticeIds.equals("")){
                for (String promo:noticeIds.split(",")){
                    int promoId= Integer.parseInt(promo);
                    delete(promoId);
                }
            }

            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 历史入园须知检索列表
     */
    @GetMapping(value = "/list")
    public CommonResult<List<GeConTouristNotice>> list(PageQuery pageQuery){
        CommonResult<List<GeConTouristNotice>> result = new CommonResult<>();
        try{
            pageQuery.setPageNum((pageQuery.getPageNum()-1)* pageQuery.getPageSize());
            List<GeConTouristNotice> list=geConTouristNoticeService.getAllNoticeByValue(pageQuery);
            /*if (list != null && list.size() > 0) {
                for (GeConTouristNotice geConTouristNotice : list) {
                    String content= UniteUtils.stripHtml(geConTouristNotice.getNoticeContent().toString());
                    if (!content.equals("")){
                        geConTouristNotice.setNoticeContent(content.substring(0,content.length()>200?200:content.length()));
                    }else {
                        geConTouristNotice.setNoticeContent("");
                    }
                }
            }*/
            pageQuery.setPageSize(0);
            List<GeConTouristNotice> list1=geConTouristNoticeService.getAllNoticeByValueNoContent(pageQuery);
            result.setCode(200);
            result.setData(list);
            result.setMessage(String.valueOf(list1.size()));
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 入园须知发布
     */
    @GetMapping(value = "/release")
    public CommonResult<JSONObject> release(){
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }

    /**
     * 入园须知取消发布
     */
    @GetMapping(value = "/unpublish")
    public CommonResult<JSONObject> unpublish(){
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }

    /**
     * 入园须知排序
     */
    @GetMapping(value = "/sort")
    public CommonResult<List<Map<String,Object>>> sort(){
        CommonResult<List<Map<String, Object>>> result = new CommonResult<>();
        return result;
    }

    /**
     * 入园须知置顶
     */
    @GetMapping(value = "/top")
    public CommonResult<JSONObject> top(){
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }


    /**
     * 入园须知审核
     */
    @GetMapping(value = "/review")
    public CommonResult<JSONObject> review( GeConTouristNotice geConTouristNotice){
        CommonResult<JSONObject> result = new CommonResult<>();
        try{
            GeConTouristNotice geConTouristNotice1=geConTouristNoticeService.queryById(geConTouristNotice.getNoticeId());
            geConTouristNotice1.setStatus(geConTouristNotice.getStatus());
            String feedback=geConTouristNotice.getFeedback();
            geConTouristNotice1.setReleasetime(new Date());
            geConTouristNoticeService.update(geConTouristNotice1);
            if (!feedback.equals("")){
                GeConTouristNoticeFeedback geConTouristNoticeFeedback = new GeConTouristNoticeFeedback();
                geConTouristNoticeFeedback.setNoticeId(geConTouristNotice.getNoticeId());
                geConTouristNoticeFeedback.setContent(feedback);
                geConTouristNoticeFeedbackService.insert(geConTouristNoticeFeedback);
            }
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 入园须知审核失败反馈
     */
    @GetMapping(value = "/feedbackInfo")
    public CommonResult<List<GeConTouristNoticeFeedback>> feedbackInfo(int noticeId){
        CommonResult<List<GeConTouristNoticeFeedback>> result = new CommonResult<>();
        try{
            List<GeConTouristNoticeFeedback> list=geConTouristNoticeFeedbackService.getinfoByNoticeId(noticeId);
            result.setData(list);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }


    /**
     * 入园须知详情
     */
    @PostMapping(value = "/details")
    @SecurityParameter
    public CommonResult<Map<String,Object>> details(@RequestBody String s){
        CommonResult<Map<String, Object>> result = new CommonResult<>();
        try{
            Integer noticeId= JSON.parseObject(s).getInteger("noticeId");
            Map<String, Object> map = new HashMap<>();
            GeConTouristNotice geConTouristNotice=geConTouristNoticeService.queryById(noticeId);
            map.put("notice",geConTouristNotice);
            List<GeConTouristNoticeUpload> geConTouristNoticeUploads=geConTouristNoticeUploadService.queryByNoticeId(noticeId);
            map.put("upload",geConTouristNoticeUploads);
            PageQuery pageQuery = new PageQuery();
             pageQuery.setReviewStatus("3");
            pageQuery.setPageSize(0);
            List<GeConTouristNotice> nlist=geConTouristNoticeService.getAllNoticeByValueNoContent(pageQuery);
            List<GeConTouristNotice> list = new ArrayList<>();
            for (int i=0;i<nlist.size();i++){
                GeConTouristNotice geConTouristNotice1=nlist.get(i);
                if (noticeId==geConTouristNotice1.getNoticeId()){
                    if (nlist.size()>=3){
                        if (i<nlist.size()-3){
                            if (i!=0){
                                map.put("up",nlist.get(i-1));
                            }else {
                                map.put("up","");
                            }
                            map.put("down",nlist.get(i+1));
                            list.add(nlist.get(i+2));
                            list.add(nlist.get(i+3));
                            map.put("more",list);
                        }else if (i==nlist.size()-3){
                            if (i!=0){
                                map.put("up",nlist.get(i-1));
                            }else {
                                map.put("up","");
                            }
                            map.put("down",nlist.get(i+1));
                           list.add(nlist.get(i+2));
                            if (nlist.size()!=3){
                                list.add(nlist.get(0));
                            }
                            map.put("more",list);
                        }else if (i==nlist.size()-2){
                            if (i!=0){
                                map.put("up",nlist.get(i-1));
                            }else {
                                map.put("up","");
                            }
                             map.put("down",nlist.get(i+1));
                            if (nlist.size()!=3){
                                list.add(nlist.get(0));
                                list.add(nlist.get(1));
                            }
                            map.put("more",list);
                        }else if (i==nlist.size()-1){
                            if (i!=0){
                                map.put("up",nlist.get(i-1));
                            }else {
                                map.put("up","");
                            }
                             map.put("down","");
                            list.add(nlist.get(0));
                            if (nlist.size()!=3){
                                list.add(nlist.get(1));
                            }
                            map.put("more",list);
                        }
                    }else {
                        if (i==0&&nlist.size()>1){
                            map.put("up","");
                            map.put("down",nlist.get(i+1));
                        }else if (i==0&&nlist.size()==1){
                            map.put("up","");
                            map.put("down","");
                        }else {
                            map.put("up",nlist.get(i-1));
                            map.put("down","");
                        }
                        map.put("more","");
                    }
                    break;
                }
            }
            result.setData(map);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }
}
